# -*- coding: utf-8 -*-
"""
@Time ： 2022/8/2 21:33
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：京东滑块验证码破解
@installer：pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
"""
import base64
import time

import pyautogui
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options

from class10.demo4 import FindPic, slide_by_pyautogui

option = Options()
# 在打开浏览器之前，去掉自动化标识
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')

##关掉密码弹窗
prefs = {}
prefs['credentials_enable_service'] = False
prefs['profile.password_manager_enabled'] = False
option.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome(options=option)
driver.maximize_window()
driver.implicitly_wait(10)

# 输入信息
driver.get('https://passport.jd.com/new/login.aspx')
driver.find_element('xpath', '//a[text()="账户登录"]').click()
driver.find_element('xpath', '//*[@id="loginname"]').send_keys('wuqingfqng1111')
driver.find_element('xpath', '//*[@id="nloginpwd"]').send_keys('djsfsdkla')
driver.find_element('xpath', '//*[@id="loginsubmit"]').click()

while True:
    # 获取背景和滑块元素
    ele_big = driver.find_element('xpath', '//div[@class="JDJRV-bigimg"]/img')
    ele_small = driver.find_element('xpath', '//div[@class="JDJRV-smallimg"]/img')
    # 获取src属性
    src_big = ele_big.get_attribute('src')
    src_small = ele_small.get_attribute('src')
    # src里面包含了图片的base64编码，截掉前缀
    base64_big = src_big[src_big.index(',') + 1:]
    base64_small = src_small[src_small.index(',') + 1:]
    # base64转二进制
    byte_big = base64.b64decode(base64_big)
    byte_small = base64.b64decode(base64_small)

    # 保存图片
    # 先打开一张图（如果没有，就会新建）
    f = open('./big.jpg', mode='wb')
    # 写入二进制
    f.write(byte_big)
    # 关闭
    f.close()

    f = open('./small.jpg', mode='wb')
    f.write(byte_small)
    f.close()

    x = FindPic()
    print(x)

    # 处理缩放
    x = int(x * 278 * 1.25 / 360)

    # 获取滑块相对网页的位置
    print(ele_small.location)

    xx = ele_small.location.get('x')
    yy = ele_small.location.get('y')
    xx = int(xx * 1.25)
    yy = int(yy * 1.25)

    slide_by_pyautogui(xx+20, yy+90+20, x)

    try:
        time.sleep(2)
        ele_small = driver.find_element('xpath', '//div[@class="JDJRV-smallimg"]/img')
        ele_x = ele_small.size.get('width')
        print(ele_small.size)
        if ele_x<1:
            break
    except Exception as e:
        print(e.__str__())
        break
